import React, { useState } from "react";
import {
  Card,
  Form,
  Input,
  Button,
  Space,
  Typography,
  Alert,
  Divider,
  message,
} from "antd";
import { UserOutlined, LockOutlined } from "@ant-design/icons";
import { getToken, getCurrentUser, isAuthenticated } from "../utils/auth";
import { AdminControllerService } from "../api";

const { Title, Text, Paragraph } = Typography;

/**
 * 登录示例组件
 * 演示如何正确处理从响应头获取token的登录流程
 */
const LoginExample: React.FC = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [loginResult, setLoginResult] = useState<{
    success: boolean;
    token?: string;
    userInfo?: any;
    error?: string;
  } | null>(null);

  // 处理登录
  const handleLogin = async (values: any) => {
    setLoading(true);
    setLoginResult(null);

    try {
      console.log("🚀 开始登录请求...");

      // 调用登录API（token会自动从响应头中提取并保存）
      const response = await AdminControllerService.loginUsingPost(values);

      console.log("✅ 登录API响应:", response);

      if (response.data) {
        // 获取保存的token
        const savedToken = getToken();
        console.log("💾 已保存的token:", savedToken);

        // 获取当前用户信息
        const currentUser = getCurrentUser();
        console.log("👤 当前用户信息:", currentUser);

        setLoginResult({
          success: true,
          token: savedToken || undefined,
          userInfo: response.data.userInfo,
        });

        message.success("登录成功！Token已从响应头中获取并保存");
      } else {
        throw new Error(response.message || "登录失败");
      }
    } catch (error: any) {
      console.error("❌ 登录失败:", error);

      const errorMessage =
        error.response?.data?.message || error.message || "登录失败";

      setLoginResult({
        success: false,
        error: errorMessage,
      });

      message.error(errorMessage);
    } finally {
      setLoading(false);
    }
  };

  // 清除登录状态
  const handleClear = () => {
    localStorage.removeItem("token");
    setLoginResult(null);
    form.resetFields();
    message.info("已清除登录状态");
  };

  return (
    <div style={{ padding: "24px", maxWidth: "800px", margin: "0 auto" }}>
      <Title level={2}>登录示例 - 从响应头获取Token</Title>

      <Alert
        message="功能说明"
        description="此示例演示如何在登录时从HTTP响应头中获取token。登录成功后，token会自动从响应头的Authorization字段中提取并保存到localStorage。"
        type="info"
        showIcon
        style={{ marginBottom: "24px" }}
      />

      <div style={{ display: "flex", gap: "24px" }}>
        {/* 登录表单 */}
        <Card title="登录表单" style={{ flex: 1 }}>
          <Form
            form={form}
            name="login"
            onFinish={handleLogin}
            layout="vertical"
            initialValues={{
              username: "admin",
              password: "123456",
            }}
          >
            <Form.Item
              name="username"
              label="用户名"
              rules={[{ required: true, message: "请输入用户名" }]}
            >
              <Input
                prefix={<UserOutlined />}
                placeholder="请输入用户名"
                size="large"
              />
            </Form.Item>

            <Form.Item
              name="password"
              label="密码"
              rules={[{ required: true, message: "请输入密码" }]}
            >
              <Input.Password
                prefix={<LockOutlined />}
                placeholder="请输入密码"
                size="large"
              />
            </Form.Item>

            <Form.Item>
              <Space>
                <Button
                  type="primary"
                  htmlType="submit"
                  loading={loading}
                  size="large"
                >
                  登录
                </Button>
                <Button onClick={handleClear} size="large">
                  清除状态
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </Card>

        {/* 登录结果 */}
        <Card title="登录结果" style={{ flex: 1 }}>
          {loginResult ? (
            <div>
              {loginResult.success ? (
                <div>
                  <Alert
                    message="登录成功"
                    type="success"
                    showIcon
                    style={{ marginBottom: "16px" }}
                  />

                  <div style={{ marginBottom: "16px" }}>
                    <Text strong>Token状态:</Text>
                    <br />
                    <Text code>
                      {loginResult.token ? "已获取并保存" : "未获取到"}
                    </Text>
                  </div>

                  {loginResult.token && (
                    <div style={{ marginBottom: "16px" }}>
                      <Text strong>Token (前20字符):</Text>
                      <br />
                      <Text code>{loginResult.token.substring(0, 20)}...</Text>
                    </div>
                  )}

                  {loginResult.userInfo && (
                    <div>
                      <Text strong>用户信息:</Text>
                      <pre
                        style={{
                          background: "#f5f5f5",
                          padding: "8px",
                          borderRadius: "4px",
                          fontSize: "12px",
                        }}
                      >
                        {JSON.stringify(loginResult.userInfo, null, 2)}
                      </pre>
                    </div>
                  )}
                </div>
              ) : (
                <Alert
                  message="登录失败"
                  description={loginResult.error}
                  type="error"
                  showIcon
                />
              )}
            </div>
          ) : (
            <div>
              <Text type="secondary">请先进行登录操作</Text>

              <Divider />

              <div>
                <Text strong>当前认证状态:</Text>
                <br />
                <Text code>{isAuthenticated() ? "已登录" : "未登录"}</Text>
              </div>

              {getToken() && (
                <div style={{ marginTop: "16px" }}>
                  <Text strong>当前Token (前20字符):</Text>
                  <br />
                  <Text code>{getToken()?.substring(0, 20)}...</Text>
                </div>
              )}
            </div>
          )}
        </Card>
      </div>

      <Divider />

      <Card title="技术说明" size="small">
        <Paragraph>
          <Text strong>Token获取流程:</Text>
        </Paragraph>
        <ol>
          <li>用户提交登录表单</li>
          <li>
            调用 <Text code>authApi.login()</Text> 方法
          </li>
          <li>
            API使用 <Text code>api.postWithHeaders()</Text>{" "}
            发送请求，返回完整响应（包含headers）
          </li>
          <li>
            调用 <Text code>extractAndSaveTokenFromResponse()</Text>{" "}
            从响应头中提取token
          </li>
          <li>Token自动保存到localStorage</li>
          <li>后续API请求会自动在请求头中添加token</li>
        </ol>

        <Paragraph>
          <Text strong>支持的响应头字段:</Text>
        </Paragraph>
        <ul>
          <li>
            <Text code>Authorization</Text> / <Text code>authorization</Text>
          </li>
          <li>
            <Text code>X-Auth-Token</Text> / <Text code>x-auth-token</Text>
          </li>
          <li>
            <Text code>Access-Token</Text> / <Text code>access-token</Text>
          </li>
        </ul>
      </Card>
    </div>
  );
};

export default LoginExample;
